package com.thenie.chat.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description 文件上传工具类
 * @Author thenie
 * @Data 2022/5/23 15:09
 */
@Component
@ConfigurationProperties(prefix = "lsky")
public class UploadUtil {

    /*
    图床上传接口
     */
    private static String imgUrl;
    /*
    图床token
     */
    private static String imgToken;

    /*
    图片访问前缀
     */
    private static String imgLookPrefix;

    /*
    默认头像相对路径位置
     */
    private static String photoDefault;

    public void setImgUrl(String imgUrl) {
        UploadUtil.imgUrl = imgUrl;
    }

    public void setImgLookPrefix(String imgLookPrefix) {
        UploadUtil.imgLookPrefix = imgLookPrefix;
    }

    public void setImgToken(String imgToken) {
        this.imgToken = imgToken;
    }
    public void setPhotoDefault(String photoDefault) {
        UploadUtil.photoDefault = photoDefault;
    }

    public static String getImgUrl() {
        return imgUrl;
    }

    public static String getImgToken() {
        return imgToken;
    }

    public static String getImgLookPrefix() {
        return imgLookPrefix;
    }

    /**
     * 默认头像，绝对路径
     * @return
     */
    public static String getPhotoDefault() {
        return imgLookPrefix+photoDefault;
    }

    /**
     * 上传图片
     * @param fileBytes
     * @param fileName
     * @return
     */
    public static HttpResponse uploadImg(byte[] fileBytes,String fileName){
        HttpResponse resp = HttpRequest.post(imgUrl)
                .header("Authorization",imgToken)
                .header("Accept", "application/json")
                .header("Content-Type", "multipart/form-data")
                .form("file", fileBytes,fileName)
                .execute();
        return resp;
    }

    /**
     * 生成唯一图片名称（包括后缀）
     * @param file
     * @return
     */
    public static String randomImgName(MultipartFile file){
        String oldName = file.getOriginalFilename();
        String extName = FileNameUtil.extName(oldName);
        String newName =IdUtil.fastSimpleUUID()+"."+extName;
        return newName;
    }

}
